﻿using UnityEngine;
using System.Collections;

public class NetworkManager : MonoBehaviour {
    string registeredGameName = "I_WANNA_MHACKS_UNITY_zwzyw952014";
    public bool isRefreshing = false;
    float refreshRequestLength = 3.0f;
    public HostData[] hostData;

    void Awake ()
    {
        DontDestroyOnLoad(this);
    }

    public void Start() {
        RefreshHostList();
    }

    public void StartServer(string roomName)
    {
        Network.InitializeServer(16, 25002, false);
        MasterServer.RegisterHost(registeredGameName, roomName, "Test");
    }

    public void ConnectToServer(int i) {
        Network.Connect(hostData[i]);
    }

    void OnServerInitialized()
    {
        Debug.Log("Server has been initialized");
        Application.LoadLevel("BaseScene");
    }

    void OnMasterServerEvent(MasterServerEvent masterServerEvent)
    {
        if (masterServerEvent == MasterServerEvent.RegistrationSucceeded)
        {
            Debug.Log("Registration successful!");
        }
    }

    public void RefreshHostList() {
        StartCoroutine("_RefreshHostList");
    }

    private IEnumerator _RefreshHostList()
    {
        Debug.Log("Refreshing...");
        isRefreshing = true;
        MasterServer.RequestHostList(registeredGameName);
        float timeStarted = Time.time;
        float timeEnd = Time.time + refreshRequestLength;

        while (Time.time < timeEnd)
        {
            hostData = MasterServer.PollHostList();
            yield return new WaitForEndOfFrame();
        }
        if (hostData == null || hostData.Length == 0)
        {
            Debug.Log("no active servers have been found.");
        }
        else
        {
            Debug.Log("find " + hostData.Length + " server.");
        }
        isRefreshing = false;
    }

    void OnPlayerConnected(NetworkPlayer player) {
        Debug.Log("Player connected from " + player.ipAddress + ":" + player.port);
    }

    void OnPlayerDisconnected(NetworkPlayer player)
    {
        Debug.Log("Player disconnected from: " + player.ipAddress + ":" + player.port);
        Network.RemoveRPCs(player);
        Network.DestroyPlayerObjects(player);
    }

    void OnApplicationQuit()
    {
        if (Network.isServer)
        {
            Network.Disconnect(200);
            MasterServer.UnregisterHost();
        }
        if (Network.isClient)
        {
            Network.Disconnect(200);
        }
    }

    void OnConnectedToServer() {
        Debug.Log("Server Connected");
        Application.LoadLevel("BaseScene");
    }
}
